import { exportToExcel } from '@/components/ExportToExcel';
import { addCustom, deleteCustom, getCustomList, updateCustom } from '@/services/api/customer';
import { addLogs } from '@/services/api/log';
import { getSelect } from '@/services/api/user';
import { DownloadOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { useAccess, useRouteProps } from '@umijs/max';
import { Button, Drawer, Form, Popconfirm, Space } from 'antd';
import moment from 'moment';
import React, { useRef, useState } from 'react';

const Customer: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const access = useAccess();
  const [form] = Form.useForm();
  const [currentId, setCurrentId] = useState<number | undefined>();
  const [list, setList] = useState<any[]>([]);
  const [drawerShow, setDrawerShow] = useState(false);
  const [items, setItems] = useState<any>({});
  const [personList, setPersonList] = useState<any>([]);
  const [selectData, setSelectData] = useState<any[]>([]);
  const [selectKeys, setSelectKeys] = useState<any[]>([]);
  const router = useRouteProps();
  const fnAddLog = async () => {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '');

    const obj = {
      user_by_id: userInfo.id,
      user_by: userInfo.nickname,
      type: 'export',
      operate: router.path.split('/')[1],
      operate_name: router.name + '表',
    };
    const res = await addLogs(obj);
    if (res) {
      actionRef.current?.reload();
    }
  };

  const fnGetDetail = (record: any) => {
    setDrawerShow(true);
    setItems({ ...record });
  };

  const columns: ProColumns[] = [
    {
      title: '客户名称',
      key: 'name',
      dataIndex: 'name',
      copyable: true,
      render: (text, record) => {
        return (
          <span style={{ cursor: 'pointer' }} onClick={() => fnGetDetail(record)}>
            {text}
          </span>
        );
      },
    },
    {
      title: '联系人',
      key: 'contact_name',
      dataIndex: 'contact_name',
      // hideInSearch: true,
    },
    {
      title: '手机号',
      key: 'phone',
      dataIndex: 'phone',
      copyable: true,
      // hideInSearch: true,
    },
    {
      title: '销售人员',
      key: 'saler_id',
      dataIndex: 'saler_id',
      valueType: 'select',
      fieldProps: {
        mode: 'multiple',
        showSearch: true,
      },
      request: async () => {
        const { data } = await getSelect({ position: '2' });
        setPersonList(data);
        return data.map((el: { id: number; nickname: string }) => {
          return {
            label: el.nickname,
            value: el.id,
          };
        });
      },
      render: (_, record) => {
        // 由于 拿取字段不同 值类型不同 即saler_id为number saler_ids为字符串 因而处理不同
        let id = record.saler_id || record.saler_ids || '';
        let arr: any = [];
        const nameArr: string[] = [];
        if (id?.split) {
          arr = id.split(',');
          if (arr.length) {
            personList.forEach((el: { id: number; nickname: string }) => {
              arr.forEach((item: string) => {
                if (el.id === Number(item)) {
                  nameArr.push(el.nickname);
                }
              });
            });
          }
        } else {
          personList.forEach((el: { id: number; nickname: string }) => {
            if (el.id === id) {
              nameArr.push(el.nickname);
            }
          });
        }
        return nameArr.join(',');
      },
    },
    {
      title: '收货地址',
      key: 'address',
      dataIndex: 'address',
      copyable: true,
      hideInSearch: true,
    },
    {
      title: '发货物流',
      key: 'shipping_logistics',
      dataIndex: 'shipping_logistics',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      key: 'created_time',
      dataIndex: 'created_time',
      valueType: 'dateRange',
      fieldProps: {
        disabledDate: (current: any) => {
          return current && current >= moment(new Date()).endOf('day');
        },
      },
      search: {
        transform: (value) => {
          return value
            ? {
                beginTime: moment(value[0]).format('YYYY-MM-DD'),
                endTime: moment(value[1]).format('YYYY-MM-DD'),
              }
            : null;
        },
      },
      render: (_, record) =>
        record.created_time ? moment(record.created_time).format('YYYY-MM-DD') : '-',
    },
    {
      title: '备注',
      key: 'remark',
      dataIndex: 'remark',
      hideInSearch: true,
      width: 180,
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'option',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record: any) => {
        return (
          <Space>
            <a
              key="edit"
              onClick={() => {
                handleUpdateModalOpen(true);
                let id: number | string[] = [];
                // const salerIds = record.saler_ids ? record.saler_id.split(',') : record.saler_id;
                // let newSalerIds: number[] = [];
                // if (salerIds?.length) {
                //   newSalerIds = salerIds.map((item: string) => Number(item));
                // }
                if (record.saler_id) {
                  id = [record.saler_id];
                } else {
                  id = record.saler_ids ? record.saler_ids.split(',') : [];
                }
                form.setFieldsValue({
                  ...record,
                  saler_id: id,
                });
                setCurrentId(record.id);
              }}
            >
              修改
            </a>
            <Popconfirm
              key="delete"
              title="删除"
              description="确定要删除该客户吗?"
              onConfirm={async () => {
                const success = await deleteCustom(record.id);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              }}
              // onCancel={cancel}
              okText="是"
              cancelText="否"
            >
              <a style={{ color: 'red' }}>删除</a>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  const fnClose = () => {
    setDrawerShow(false);
  };
  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        pagination={{
          showSizeChanger: true,
        }}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
              form.resetFields();
            }}
          >
            <PlusOutlined /> 新增
          </Button>,
          access.canAdmin ? (
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                const info = selectData.length ? selectData : list;
                info.forEach((el: { saler_id: number | string; created_time: any }) => {
                  el.created_time = el.created_time
                    ? moment(el.created_time).format('YYYY-MM-DD')
                    : '';
                  personList.find((item: { nickname: string; id: number }) => {
                    if (item.id === el.saler_id) {
                      el.saler_id = item.nickname;
                    }
                    return el;
                  });
                });
                exportToExcel(columns, info, router.name);
                fnAddLog();
              }}
            >
              <DownloadOutlined /> 导出
            </Button>
          ) : null,
        ]}
        request={async (params) => {
          setSelectData([]);
          setSelectKeys([]);
          const data = await getCustomList(params);
          setList(data.data);
          return data;
        }}
        columns={columns}
        rowSelection={{
          onChange: (key, data) => {
            setSelectData(data);
            setSelectKeys(key);
          },
          selectedRowKeys: selectKeys,
          fixed: 'left',
        }}
        tableAlertRender={({ selectedRowKeys }) => {
          return (
            <Space size={24}>
              <span>已选 {selectedRowKeys.length} 项</span>
            </Space>
          );
        }}
      />
      <ModalForm
        title={'新增客户'}
        form={form}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const obj = { ...value, saler_id: value.saler_id?.join(',') };
          const success = await addCustom(obj);
          if (success?.code === 200) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        modalProps={{
          destroyOnClose: true,
        }}
      >
        <ProFormText
          label="客户名称"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="name"
        />

        <ProFormText
          label="联系人"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="contact_name"
        />

        <ProFormText
          label="发货物流"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="shipping_logistics"
        />

        <ProFormText
          label="手机号"
          rules={[
            {
              required: false,
              message: '请输入',
            },
          ]}
          name="phone"
        />

        <ProFormSelect
          label="销售人员"
          rules={[
            {
              required: true,
              message: '请选择',
            },
          ]}
          fieldProps={{
            showSearch: true,
            mode: 'multiple',
          }}
          request={async () => {
            const { data } = await getSelect({ position: '2' });

            return data.map((el: { id: number; nickname: string }) => {
              return {
                label: el.nickname,
                value: el.id,
              };
            });
          }}
          name="saler_id"
        />

        <ProFormTextArea
          label="收货地址"
          fieldProps={{
            maxLength: 200,
          }}
          rules={[
            {
              required: false,
              message: '请输入',
            },
          ]}
          name="address"
        />
        <ProFormTextArea
          label="备注"
          fieldProps={{
            maxLength: 200,
          }}
          rules={[
            {
              required: false,
              message: '请输入',
            },
          ]}
          name="remark"
        />
      </ModalForm>

      <ModalForm
        title={'修改客户'}
        form={form}
        open={updateModalOpen}
        onOpenChange={handleUpdateModalOpen}
        onFinish={async (value) => {
          const obj = { ...value, id: currentId, saler_id: value.saler_id?.join(',') };
          const success = await updateCustom({ ...obj });
          if (success?.code === 200) {
            handleUpdateModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        modalProps={{
          destroyOnClose: true,
        }}
      >
        <ProFormText
          label="客户名称"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="name"
        />

        <ProFormText
          label="联系人"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="contact_name"
        />

        <ProFormText
          label="发货物流"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="shipping_logistics"
        />

        <ProFormText
          label="手机号"
          rules={[
            {
              required: false,
              message: '请输入',
            },
          ]}
          name="phone"
        />

        <ProFormSelect
          label="销售人员"
          rules={[
            {
              required: true,
              message: '请选择',
            },
          ]}
          fieldProps={{
            showSearch: true,
            mode: 'multiple',
          }}
          request={async () => {
            const { data } = await getSelect({ position: '2' });

            return data.map((el: { id: number; nickname: string }) => {
              return {
                label: el.nickname,
                value: el.id,
              };
            });
          }}
          name="saler_id"
        />

        <ProFormTextArea
          label="收货地址"
          fieldProps={{
            maxLength: 200,
          }}
          rules={[
            {
              required: false,
              message: '请输入',
            },
          ]}
          name="address"
        />
        <ProFormTextArea
          label="备注"
          fieldProps={{
            maxLength: 200,
          }}
          rules={[
            {
              required: false,
              message: '请输入',
            },
          ]}
          name="remark"
        />
      </ModalForm>
      <Drawer width="40%" title="客户信息详情" onClose={fnClose} open={drawerShow}>
        <ProDescriptions
          request={async () => {
            return Promise.resolve({
              success: true,
              data: items,
            });
          }}
          column={2}
        >
          <ProDescriptions.Item dataIndex="name" label="客户名称" />
          <ProDescriptions.Item dataIndex="phone" label="手机号" />
          <ProDescriptions.Item
            dataIndex="saler_id"
            label="销售人员"
            request={async () => {
              const { data } = await getSelect({ position: '2' });
              return data.map((el: { id: number; nickname: string }) => {
                return {
                  label: el.nickname,
                  value: el.id,
                };
              });
            }}
          />
          <ProDescriptions.Item dataIndex="address" label="收货地址" />
          <ProDescriptions.Item dataIndex="remark" span={2} label="备注" />
        </ProDescriptions>
      </Drawer>
    </PageContainer>
  );
};

export default Customer;
